import { Args, Mutation, Resolver, Context } from '@nestjs/graphql';
import bcrypt from 'bcrypt';
import { AuthenticationError } from 'apollo-server';

import { LoginDTO } from './dto/login.dto';
import { prisma } from '../generated/prisma-client/sys';

@Resolver('AuthPayload')
export class AuthResolber {
  @Mutation('login')
  async login(
    @Args('user') { username, password }: LoginDTO,
    @Context() ctx: any,
  ) {
    const user = await prisma.sysUser({ username });

    if (!user || !(await bcrypt.compare(password, user.password))) {
      throw new AuthenticationError('用户名或密码错误！');
    }

    const roles = await prisma.sysRoles({
      where: { users_some: { id: user.id } },
    });

    const authorities = await prisma.sysAuthorities({
      where: { roles_some: { id_in: roles.map(({ id }) => id) } },
    });

    ctx.request.session.auth = { user, authorities };
    return { user, authorities };
  }

  @Mutation('logout')
  async logout(@Context() ctx: any): Promise<any> {
    const auth = ctx.request.session.auth;
    if (!auth) {
      throw new AuthenticationError('用户未登录！');
    }

    ctx.request.session.destroy(() => {
      // session destroyed
    });
    return auth;
  }
}
